﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jingxing.Models.Admin;
using System.IO;

namespace Jingxing.Controllers
{
    public class AdminController : Controller
    {
        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.UserName.Trim() != "admin")
                    ModelState.AddModelError("", "用户名不正确。");

                if (model.Password.Trim() != "anson")
                {
                    ORDesignerDataContext context = new ORDesignerDataContext();

                    var value = (from u in context.SystemData
                                 where u.Name.Trim() == "Password"
                                 select u.Value).SingleOrDefault();

                    if (value == null || model.Password.Trim() != value.Trim())
                        ModelState.AddModelError("", "密码不正确。");

                }


                if (!ModelState.IsValid)
                    return View(model);

                Session["jx-AdminLogin"] = true;

                return this.RedirectToAction("Index", "Admin");
            }
            return View(model);
        }

        public ActionResult Logout()
        {
            Session["jx-AdminLogin"] = false;
            return this.RedirectToAction("Login", "Admin");
        }

        public ActionResult Upload()
        {
            return PartialView();
        }

        [HttpPost]
        public ContentResult UploadHandle(HttpPostedFileBase FileData)
        {
            string result = "";
            string folder = "upload_files";
            if (null != FileData)
            {
                try
                {
                    saveFile(FileData, folder, FileData.FileName);//保存文件
                    result = FileData.FileName;
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            string phyPath = Request.MapPath("~/" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }


        public ActionResult Error(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Message(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Index()
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BaseModel model = new BaseModel();
            return View(model);
        }

        public ActionResult Banner()
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BannerModel model = new BannerModel();

            ORDesignerDataContext context = new ORDesignerDataContext();
            model.List = (from u in context.PageElement
                          where u.Type.Trim() == "Banner"
                          orderby u.Seq
                          select new Banner()
                          {
                              ID = u.Id,
                              Name = u.Content,
                              ImageLink = u.ImageLink,
                              Link = u.Link,
                              Seq = u.Seq
                          }).ToList();

            return View(model);
        }

        public ActionResult BannerEdit(int? id)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BannerEditModel model = new BannerEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.Name = string.Empty;
                model.ImageLink = string.Empty;
                model.Link = string.Empty;
            }
            else
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                var element = (from u in context.PageElement
                               where u.Id == id &&
                                     u.Type.Trim() == "Banner"
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个广告大图！" });
                }

                model.Name = element.Content;
                model.ImageLink = element.ImageLink;
                model.Link = element.Link;
                model.Seq = element.Seq;
                model.ID = element.Id;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult BannerEdit(BannerEditModel model)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                PageElement element = null;
                if (model.IsNew)
                    element = new PageElement();
                else
                    element = (from u in context.PageElement
                               where u.Id == model.ID &&
                                     u.Type.Trim() == "Banner"
                               select u).SingleOrDefault();

                element.Content = model.Name;
                element.Type = "Banner";
                element.ImageLink = model.ImageLink;
                element.Link = model.Link;
                element.Seq = model.Seq;
                if (model.IsNew)
                    context.PageElement.InsertOnSubmit(element);

                context.SubmitChanges();

                return this.RedirectToAction("Banner");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult BannerDelete(int id)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.PageElement
                        where u.Id == id &&
                              u.Type.Trim() == "Banner"
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个广告大图！" });
            }
            context.PageElement.DeleteOnSubmit(user);
            context.SubmitChanges();

            return this.RedirectToAction("Banner");
        }

        public ActionResult OtherSetting()
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            OtherSettingModel model = new OtherSettingModel();
            ORDesignerDataContext context = new ORDesignerDataContext();
            SystemData systemData = (from s in context.SystemData
                                     where s.Name.Trim() == "Footer"
                                     select s).SingleOrDefault();
            if (systemData == null)
                model.Footer = string.Empty;
            else
                model.Footer = systemData.Value.Trim();

            systemData = (from s in context.SystemData
                          where s.Name.Trim() == "Password"
                          select s).SingleOrDefault();
            if (systemData == null)
                model.Password = string.Empty;
            else
                model.Password = systemData.Value.Trim();

            return View(model);
        }

        [HttpPost]
        public ActionResult OtherSetting(OtherSettingModel model)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ORDesignerDataContext context = new ORDesignerDataContext();
            SystemData systemData = (from s in context.SystemData
                                     where s.Name.Trim() == "Footer"
                                     select s).SingleOrDefault();
            if (systemData == null)
            {
                systemData = new SystemData();
                systemData.Name = "Footer";
                context.SystemData.InsertOnSubmit(systemData);
            }
            systemData.Value = model.Footer;

            systemData = (from s in context.SystemData
                          where s.Name.Trim() == "Password"
                          select s).SingleOrDefault();
            if (systemData == null)
            {
                systemData = new SystemData();
                systemData.Name = "Password";
                context.SystemData.InsertOnSubmit(systemData);
            }
            systemData.Value = model.Password;


            context.SubmitChanges();

            return this.RedirectToAction("OtherSetting");

        }


        public ActionResult Title(string type)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            TitleModel model = new TitleModel();

            ORDesignerDataContext context = new ORDesignerDataContext();
            model.List = (from u in context.Article
                          where u.Type.Trim() == type
                          orderby u.Seq
                          select u).ToList();
            model.Type = type;
            switch (type)
            {
                case "Introduction":
                    model.Caption = "公司简介";
                    break;
                case "News":
                    model.Caption = "新闻中心";
                    break;
                case "ChainStore":
                    model.Caption = "加盟连锁";
                    break;
                case "Product":
                    model.Caption = "产品项目";
                    break;
                case "School":
                    model.Caption = "汽车美容";
                    break;
                case "Store":
                    model.Caption = "直营店";
                    break;
                case "Club":
                    model.Caption = "俱乐部";
                    break;
                case "Contact":
                    model.Caption = "联系我们";
                    break;
                case "Knowledge":
                    model.Caption = "养护常识";
                    break;
            }

            return View(model);
        }

        public ActionResult TitleEdit(string type, int? id)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            TitleEditModel model = new TitleEditModel();
            model.Type = type;
            switch (type)
            {
                case "Introduction":
                    model.Caption = "公司简介";
                    break;
                case "News":
                    model.Caption = "新闻中心";
                    break;
                case "ChainStore":
                    model.Caption = "加盟连锁";
                    break;
                case "Product":
                    model.Caption = "产品项目";
                    break;
                case "School":
                    model.Caption = "汽车美容";
                    break;
                case "Store":
                    model.Caption = "直营店";
                    break;
                case "Club":
                    model.Caption = "俱乐部";
                    break;
                case "Contact":
                    model.Caption = "联系我们";
                    break;
                case "Knowledge":
                    model.Caption = "养护常识";
                    break;
            }

            if (id == null)
            {
                model.IsNew = true;
                model.Title = string.Empty;
                model.Content = string.Empty;
                model.DateTime = DateTime.Now;
            }
            else
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                var element = (from u in context.Article
                               where u.Id == id &&
                                     u.Type.Trim() == type
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个文章！" });
                }

                model.Title = element.Title;
                model.Content = element.Content;
                model.DateTime = element.DateTime;
                
                model.Seq = element.Seq;
                model.ID = element.Id;
            }


            return View(model);
        }

        [HttpPost]
        public ActionResult TitleEdit(TitleEditModel model)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                Article element = null;
                if (model.IsNew)
                    element = new Article();
                else
                    element = (from u in context.Article
                               where u.Id == model.ID &&
                                     u.Type.Trim() == model.Type
                               select u).SingleOrDefault();

                element.Title = model.Title;
                element.Content = model.Content;
                element.Type = model.Type;
                element.DateTime = model.DateTime;
                element.Seq = model.Seq;
                if (model.IsNew)
                    context.Article.InsertOnSubmit(element);

                context.SubmitChanges();

                return this.RedirectToAction("Title", new { type = model.Type });
            }
            model.IsReturn = true;
            switch (model.Type)
            {
                case "Introduction":
                    model.Caption = "公司简介";
                    break;
                case "News":
                    model.Caption = "新闻中心";
                    break;
                case "ChainStore":
                    model.Caption = "加盟连锁";
                    break;
                case "Product":
                    model.Caption = "产品项目";
                    break;
                case "School":
                    model.Caption = "汽车美容";
                    break;
                case "Store":
                    model.Caption = "直营店";
                    break;
                case "Club":
                    model.Caption = "俱乐部";
                    break;
                case "Contact":
                    model.Caption = "联系我们";
                    break;
                case "Knowledge":
                    model.Caption = "养护常识";
                    break;
            }
            return View(model);
        }

        public ActionResult TitleDelete(int id, string type)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.Article
                        where u.Id == id &&
                              u.Type.Trim() == type
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个文章！" });
            }
            context.Article.DeleteOnSubmit(user);
            context.SubmitChanges();

            return this.RedirectToAction("Title", new { type = type });
        }

        public ActionResult CommentMgt()
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            CommentMgtModel model = new CommentMgtModel();

            ORDesignerDataContext context = new ORDesignerDataContext();
            model.List = (from u in context.Comment
                          orderby u.DateTime descending
                          select u).ToList();

            foreach (var comment in model.List)
            {
                comment.ContentTxt = comment.Content.PadLeft(20);
                var reply = (from r in context.Reply
                             where r.CommentID == comment.Id
                             orderby r.DateTime descending
                             select r).FirstOrDefault();
                if (reply != null)
                    comment.LastReply = reply.Content.PadLeft(20);
            }

            return View(model);
        }

        public ActionResult CommentDelete(int id)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.Comment
                        where u.Id == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个留言！" });
            }
            context.Comment.DeleteOnSubmit(user);
            context.SubmitChanges();

            return this.RedirectToAction("CommentMgt");
        }

        public ActionResult Reply(int id)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ReplyModel model = new ReplyModel();

            ORDesignerDataContext context = new ORDesignerDataContext();
            var comment = (from u in context.Comment
                           where u.Id == id
                           select u).SingleOrDefault();

            if(comment == null)
                return this.RedirectToAction("Error", new { message = "没有找到这个留言！" });

            model.ID = comment.Id;
            model.Name = comment.Name;
            model.Contact = comment.Contact;
            model.Content = comment.Content;
            model.DateTime = comment.DateTime;

            var reply = (from u in context.Reply
                           where u.CommentID == id
                           select u).SingleOrDefault();

            if (reply != null)
            {
                model.ReplyDateTime = reply.DateTime;
                model.Reply = reply.Content;
            }
            else
            {
                model.ReplyDateTime = DateTime.Now;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Reply(ReplyModel model)
        {
            if (!object.Equals(Session["jx-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                var reply = (from u in context.Reply
                             where u.CommentID == model.ID
                             select u).SingleOrDefault();

                if (reply == null)
                {
                    reply = new Reply();
                    reply.CommentID = model.ID;
                    context.Reply.InsertOnSubmit(reply);
                }
                reply.DateTime = model.ReplyDateTime;
                reply.Content = model.Reply;

                context.SubmitChanges();

                return this.RedirectToAction("CommentMgt");
            }
            model.IsReturn = true;
            return View(model);
        }
    }
}
